package com.logic.landseaserver.models.payment.ws;

import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.logic.common.enums.HttpCodeEnum;
import com.logic.common.util.CommonResult;
import com.logic.common.util.CommonResultMap;
import com.logic.landseaserver.common.exception.LandseaException;
import com.logic.landseaserver.common.util.LoggerHelper;
import com.logic.landseaserver.common.util.StringTools;
import com.logic.landseaserver.domain.ShiJiProjectConfig;
import com.logic.landseaserver.models.payment.bean.ShiJiPaymentResponse;
import com.logic.landseaserver.models.payment.bean.ShiJiPosPaymentResponse;
import com.logic.landseaserver.models.payment.service.PaymentService;
import com.logic.landseaserver.models.payment.service.ShiJiPaymentService;
import com.logic.landseaserver.models.payment.util.ShiJiPosDesUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 
 *
 * 项目名称：system-server</br>
 * 类名称：ShiJiPaymentManageRest</br>
 * 类描述：银石</br>
 * 创建人：Aaron</br>
 * 创建时间：2017年7月17日 下午2:35:52</br>
 * 
 * @version 1.0
 *
 */
@Path("/payment")
@Api(value = "银石支付管理")
public class ShiJiPaymentManageRest
{
    protected static final Logger LOGGER = LoggerFactory.getLogger(ShiJiPaymentManageRest.class);
    
    /** 支付入口组件 **/
    @Autowired
    private PaymentService paymentService;
    
    /** 银石支付管理 **/
    @Autowired
    private ShiJiPaymentService shiJiPaymentService;
    
    /**
     * 
     * [简要描述]：查询待支付的记录</br>
     * [详细描述]：银石智能POS扫码读取</br>
     * [作者]：Aaron(2017-07-17)</br>
     *
     * @param paymentId 支付记录Id
     * @return
     *
     */
    @GET
    @Path("/getPaymentRecord/{paymentId}")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "查询待支付的记录,银石智能POS扫码读取")
    public Response getPaymentRecord(
        @ApiParam(value = "paymentId", required = true) @PathParam("paymentId") Integer paymentId)
    {
        CommonResultMap map = new CommonResultMap();
        try
        {
            LOGGER.info("PaymentRest|getPaymentRecord|paymentId=" + paymentId);
            
            Map<String, Object> result = shiJiPaymentService.getPaymentRecord(paymentId);
            
            LOGGER.info("PaymentRest|getPaymentRecord|QueryResult=" + result.toString());
            map.setData(result);
            map.setResult(CommonResult.SUCCESS);
        }
        catch (LandseaException e)
        {
            // 报错时不能抛出框架及错误,直接返回空
            Map<String, Object> errorResult = new HashMap<String, Object>();
            map.setData(errorResult);
            map.setResult(CommonResult.SUCCESS);
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
    
    /**
     * 
     * [简要描述]：支付回调-银石POS</br>
     * [详细描述]：</br>
     * [作者]：Aaron(2017-07-19)</br>
     *
     * @param paymentRequest
     * @return
     *
     */
    @POST
    @Path("/paymentResponse/ShiJiPos")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "支付回调-银石POS")
    public Response payPosCallback(
        @ApiParam(value = "paymentResponse", required = true) Map<String,Object> paymentResponseMap)
    {
        LOGGER.info("payCallback|银石POS支付结果通知|" + paymentResponseMap);
        
        CommonResultMap map = new CommonResultMap();
        try
        {
            String paymentencrt = StringTools.getString(paymentResponseMap.get("paymentId"));
            String paymentIdStr = ShiJiPosDesUtil.decrypt(paymentencrt);
            
            ShiJiPosPaymentResponse paymentResponse = new ShiJiPosPaymentResponse();
            paymentResponse.setPaymentId(paymentIdStr);
            paymentResponse.setPayResult(StringTools.getString(paymentResponseMap.get("payResult")));
            paymentResponse.setMsg(StringTools.getString(paymentResponseMap.get("msg")));
            paymentResponse.setTransactionNo(StringTools.getString(paymentResponseMap.get("transactionNo")));
            
            // 对paymentId解密
            
            Map<String, Object> resultMap = paymentService.payCallback(paymentResponse.getPaymentId(), paymentResponse);
            if (MapUtils.isNotEmpty(resultMap))
            {
                LOGGER.info("paymentResponse|Return Data|" + resultMap.toString());
                map.setData(resultMap);
            }
            
            map.setResult(CommonResult.SUCCESS);
        }
        catch (LandseaException e)
        {
            LOGGER.error("payCallback|银石智能POS支付通知处理失败|", e.getErrorMsg());
            
            // 回调收到结果对于第三方来讲已经是成功的
            Map<String, Object> resultMap = new HashMap<String, Object>();
            // 0成功，其他失败
            resultMap.put("status", -1);
            resultMap.put("msg", e.getErrorDesc());
            map.setResult(CommonResult.SUCCESS);
            map.setData(resultMap);
        }
        catch (Exception e)
        {
            LOGGER.info("payCallback|银石智能POS支付通知处理失败|", e);
            
            // 回调收到结果对于第三方来讲已经是成功的
            Map<String, Object> resultMap = new HashMap<String, Object>();
            // 0成功，其他失败
            resultMap.put("status", -1);
            resultMap.put("msg", "参数错误");
            map.setResult(CommonResult.SUCCESS);
            map.setData(resultMap);
        }
        
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
    
    /***
     * 
     * [简要描述]：支付回调-银石回调，包含支付宝、微信、移动端银石收银台回调</br>
     * [详细描述]：</br>
     * [作者]：Aaron(2017-07-19)</br>
     *
     * @param paymentRequest
     * @return
     *
     */
    @POST
    @Path("/paymentResponse/ShiJi")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "支付回调-银石支付(非pos)")
    public Response payCallback(
        @ApiParam(value = "paymentResponse", required = true) Map<String,Object> paymentResponse)
    {
        LOGGER.info("payCallback|银石支付结果通知|" + paymentResponse);
        
        CommonResultMap map = new CommonResultMap();
        try
        {
            ShiJiPaymentResponse shiJiPaymentResponse = shiJiPaymentService.buildResponseFromRespMap(paymentResponse);
            
            Map<String, Object> resultMap =
                paymentService.payCallback(shiJiPaymentResponse.getOrgTxnNo(), shiJiPaymentResponse);
            if (MapUtils.isNotEmpty(resultMap))
            {
                LOGGER.info("payCallback|Return Data|" + resultMap.toString());
                map.setData(resultMap);
            }
            
            map.setResult(CommonResult.SUCCESS);
        }
        catch (LandseaException e)
        {
            LOGGER.info("payCallback|银石支付结果通知处理失败|", e.getErrorMsg());
            
            // 回调收到结果对于第三方来讲已经是成功的
            Map<String, Object> resultMap = new HashMap<String, Object>();
            // 0成功，其他失败
            resultMap.put("status", -1);
            resultMap.put("msg", e.getErrorDesc());
            map.setResult(CommonResult.SUCCESS);
            map.setData(resultMap);
        }
        catch (Exception e)
        {
            LOGGER.info("payCallback|银石支付结果通知处理失败|", e);
            
            // 回调收到结果对于第三方来讲已经是成功的
            Map<String, Object> resultMap = new HashMap<String, Object>();
            // 0成功，其他失败
            resultMap.put("status", -1);
            resultMap.put("msg", "未知异常");
            map.setResult(CommonResult.SUCCESS);
            map.setData(resultMap);
        }
        
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
    
    /**
     * 
     * [简要描述]：保存项目配置项</br>
     * [详细描述]：不存在走新增，存在走更新</br>
     * [作者]：Aaron(2017-07-21)</br>
     *
     * @param projectConfigArray 云丁项目配置数组
     * @return 结果
     *
     */
    @POST
    @Path("/shijiPay/saveProjectConfigs")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "保存银石支付项目配置")
    public Response saveShiJiProjectConfigs(
        @ApiParam(value = "shiJiProjectConfig", required = true) ShiJiProjectConfig shiJiProjectConfig)
    {
        CommonResultMap map = new CommonResultMap();
        try
        {
            shiJiPaymentService.saveShiJiProjectConfig(shiJiProjectConfig);
            map.setResult(CommonResult.SUCCESS);
        }
        catch (LandseaException e)
        {
            LoggerHelper.handleException(LOGGER, "saveProjectConfigs", e, map);
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
    
    /**
     * 
     * [简要描述]：查询项目银石配置</br>
     * [详细描述]：不存在走新增，存在走更新</br>
     * [作者]：Aaron(2017-06-26)</br>
     *
     * @param projectId 项目Id
     * @return 结果
     *
     */
    @GET
    @Path("/shijiPay/getProjectConfig/{projectId}")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "get project configs.")
    public Response getShiJiProjectConfig(@ApiParam(value = "projectId", required = true) @PathParam("projectId") Integer projectId)
    {
        CommonResultMap map = new CommonResultMap();
        try
        {
            ShiJiProjectConfig shiJiProjectConfig = shiJiPaymentService.getShiJiProjectConfig(projectId);
            map.setData(shiJiProjectConfig);
            map.setResult(CommonResult.SUCCESS);
        }
        catch (LandseaException e)
        {
            LoggerHelper.handleException(LOGGER, "getProjectConfigs", e, map);
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
}
